<template>
  <view class="container">
    <!-- 支付信息 -->
    <view class="payment-info">
      <view class="price-section">
        <text class="price-label">支付金额</text>
        <text class="price-value">¥{{ formatPrice(amount) }}</text>
      </view>
      <view class="order-info">
        <text class="order-label">订单编号</text>
        <text class="order-value">{{ orderInfo.orderNo || '加载中...' }}</text>
      </view>
      <view class="time-info">
        <text class="time-label">下单时间</text>
        <text class="time-value">{{ orderInfo.createdAtStr || '加载中...' }}</text>
      </view>
    </view>

    <!-- 支付方式 -->
    <view class="payment-methods">
      <view class="section-title">支付方式</view>
      <view class="methods-list">
        <view 
          v-for="(method, index) in paymentMethods" 
          :key="index" 
          class="payment-method"
          :class="{ active: selectedMethod === method.value }"
          @click="selectMethod(method.value)"
        >
          <image :src="method.icon" class="method-icon" mode="aspectFit"></image>
          <view class="method-info">
            <text class="method-name">{{ method.name }}</text>
            <text class="method-desc">{{ method.desc }}</text>
          </view>
          <image 
            :src="selectedMethod === method.value ? '/static/images/radio-checked.png' : '/static/images/radio-unchecked.png'" 
            class="select-icon"
            mode="aspectFit"
          ></image>
        </view>
      </view>
    </view>

    <!-- 支付按钮 -->
    <view class="pay-btn-area">
      <button 
        class="pay-btn" 
        :disabled="!selectedMethod || loading" 
        @click="handlePayOrder"
      >
        {{ loading ? '支付中...' : '立即支付' }}
      </button>
    </view>

    <!-- 温馨提示 -->
    <view class="tips">
      <text class="tips-title">温馨提示</text>
      <text class="tip-item">1. 请在30分钟内完成支付，否则订单将自动取消。</text>
      <text class="tip-item">2. 支付成功后，您可以在"我的订单"中查看订单详情。</text>
      <text class="tip-item">3. 如有疑问，请联系客服。</text>
    </view>

    <!-- 其他操作 -->
    <view class="other-actions">
      <text class="action-item" @click="handleCancelOrder">取消订单</text>
      <text class="action-item" @click="goToOrderDetail">查看订单详情</text>
      <text class="action-item" @click="contactService">联系客服</text>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { onLoad,onShow} from '@dcloudio/uni-app';
import { getOrderDetail, payOrder, cancelOrder } from '../../api/order.js';
import { cartApi } from '../../api/cart.js';

// 页面参数
const orderId = ref(null);
const amount = ref(0);

// 订单信息
const orderInfo = ref({});

// 支付状态
const loading = ref(false);
const selectedMethod = ref('wechat');

// 支付方式列表
const paymentMethods = [
  {
    name: '微信支付',
    value: 'wechat',
    icon: '/static/images/wechat-pay.png',
    desc: '推荐使用微信支付'
  },
  {
    name: '支付宝',
    value: 'alipay',
    icon: '/static/images/alipay.png',
    desc: '支付宝付款'
  },
  {
    name: '余额支付',
    value: 'balance',
    icon: '/static/images/balance-pay.png',
    desc: '使用账户余额支付'
  }
];

// 格式化价格
const formatPrice = (price) => {
  if (price === undefined || price === null) return '0.00';
  let numPrice = typeof price === 'string' ? parseFloat(price) : Number(price);
  if (isNaN(numPrice)) return '0.00';
  return numPrice.toFixed(2);
};

// 选择支付方式
const selectMethod = (method) => {
  selectedMethod.value = method;
};

// 加载订单信息
const loadOrderInfo = async () => {
  if (!orderId.value) return;
  
  try {
    uni.showLoading({ title: '加载中...' });
    const res = await getOrderDetail(orderId.value);
    
    if (res.code === 200 && res.data) {
      orderInfo.value = res.data;
      // 修正金额显示
      amount.value = res.data.totalAmount || 0;
      // 如果订单已经支付，跳转到订单详情
      if (res.data.status === 'paid' || res.data.status === 'shipping' || res.data.status === 'completed') {
        uni.showToast({
          title: '订单已支付',
          icon: 'success'
        });
        setTimeout(() => {
          goToOrderDetail();
        }, 1500);
      }
    } else {
      uni.showToast({
        title: res.msg || '获取订单信息失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单信息失败:', error);
    uni.showToast({
      title: '获取订单信息失败',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 支付订单
const handlePayOrder = async () => {
  if (!selectedMethod.value) {
    uni.showToast({
      title: '请选择支付方式',
      icon: 'none'
    });
    return;
  }
  
  try {
    loading.value = true;
    const res = await payOrder(orderId.value, selectedMethod.value);
    
    if (res.code === 200) {
      // 支付成功，模拟支付流程
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      });
      
      // 清除购物车中已购买的商品
      try {
        // 如果是从购物车下单的，需要清除购物车中对应的商品
        if (orderInfo.value.cartItemIds) {
          const cartItemIds = orderInfo.value.cartItemIds.split(',');
          await cartApi.batchDeleteCartItems(cartItemIds);
          
          // 更新购物车角标
          const cartCountRes = await cartApi.getCartCount();
          if (cartCountRes.code === 200) {
            // 更新tabBar购物车角标
            uni.setTabBarBadge({
              index: 2, // 购物车的tabBar索引
              text: cartCountRes.data > 0 ? String(cartCountRes.data) : ''
            });
          }
        }
      } catch (e) {
        console.error('清除购物车失败:', e);
      }
      
      // 延迟跳转到订单详情页
      setTimeout(() => {
        uni.redirectTo({
          url: `/pages/order/detail?id=${orderId.value}`
        });
      }, 1500);
    } else {
      uni.showToast({
        title: res.msg || '支付失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('支付失败:', error);
    uni.showToast({
      title: '支付失败，请稍后再试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 取消订单
const handleCancelOrder = () => {
  uni.showModal({
    title: '提示',
    content: '确定要取消订单吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '取消中...' });
          const response = await cancelOrder(orderId.value, '用户主动取消');
          
          if (response.code === 200) {
            uni.showToast({
              title: '订单已取消',
              icon: 'success'
            });
            
            // 返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: response.msg || '取消订单失败',
              icon: 'none'
            });
          }
        } catch (error) {
          console.error('取消订单失败:', error);
          uni.showToast({
            title: '取消订单失败',
            icon: 'none'
          });
        } finally {
          uni.hideLoading();
        }
      }
    }
  });
};

// 查看订单详情
const goToOrderDetail = () => {
  uni.redirectTo({
    url: `/pages/order/detail?id=${orderId.value}`
  });
};

// 联系客服
const contactService = () => {
  uni.showToast({
    title: '客服功能暂未开放',
    icon: 'none'
  });
};

// 获取页面参数
onLoad((options) => {
  // 兼容 order_id 和 orderId 两种参数
  if (options.order_id) {
    orderId.value = options.order_id;
  } else if (options.orderId) {
    orderId.value = options.orderId;
  }
  if (options.amount) {
    amount.value = options.amount;
  }
});

// 页面加载时获取订单信息
onMounted(() => {
  loadOrderInfo();
});

// 当用户返回页面时，确保数据重新加载
onShow(() => {
  if (orderId.value) {
    loadOrderInfo();
  }
});
</script>

<style>
.container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding: 30rpx;
}

.payment-info {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.price-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30rpx;
  padding-bottom: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.price-label {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.price-value {
  font-size: 60rpx;
  font-weight: bold;
  color: #ff6700;
}

.order-info, .time-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20rpx;
}

.order-label, .time-label {
  font-size: 28rpx;
  color: #666;
}

.order-value, .time-value {
  font-size: 28rpx;
  color: #333;
}

.payment-methods {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.methods-list {
  border-radius: 12rpx;
  overflow: hidden;
}

.payment-method {
  display: flex;
  align-items: center;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.payment-method:last-child {
  border-bottom: none;
}

.payment-method.active {
  background-color: #fff7f5;
}

.method-icon {
  width: 60rpx;
  height: 60rpx;
  margin-right: 20rpx;
}

.method-info {
  flex: 1;
}

.method-name {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 5rpx;
}

.method-desc {
  font-size: 24rpx;
  color: #999;
}

.select-icon {
  width: 40rpx;
  height: 40rpx;
}

.pay-btn-area {
  margin: 30rpx 0;
}

.pay-btn {
  width: 100%;
  height: 90rpx;
  line-height: 90rpx;
  background-color: #ff6700;
  color: #fff;
  font-size: 32rpx;
  border-radius: 45rpx;
}

.pay-btn[disabled] {
  background-color: #ccc;
}

.tips {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.tips-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.tip-item {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 10rpx;
  display: block;
}

.other-actions {
  display: flex;
  justify-content: space-around;
  padding: 20rpx 0;
}

.action-item {
  font-size: 28rpx;
  color: #666;
  text-decoration: underline;
}
</style> 